


import 'package:alip_app/AppStates/NetworkApi.dart';
import 'package:alip_app/AppStates/TopicState.dart';
import 'package:alip_app/Entities/GetTopicResult.dart';
import 'package:alip_app/StateManagement/ModelProvider.dart';
import 'package:alip_app/UI/Pages/TopicDetailsPage.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart' as Intl;

class TopicsPage extends StatefulWidget {
  final int boardId;
  final double paddingHeight;
  final String orderBy;
  final String filterType;
  final int pageIndex;
  TopicsPage({this.boardId = 0, this.paddingHeight = 0.0, this.orderBy, this.filterType, this.pageIndex});
  @override
  State<StatefulWidget> createState() {
    return _TopicsPageState();
  }
}

class _TopicsPageState extends State<TopicsPage> with AutomaticKeepAliveClientMixin {

  @override
  Widget build(BuildContext context) {
    super.build(context);

    final networkApi = ModelContainer.of<NetworkApi>(context).model.api;
    Widget buildingWidget = FutureBuilder<List<Topic>>(
      future: () async {
//          if (data.topics.isEmpty) {
        final topics = (await networkApi.getTopics(size: 20, page: 1, boardId: this.widget.boardId, filterType: this.widget.filterType, orderBy: this.widget.orderBy)).list;
//            data.topics.addAll(topics);
//          }
        return topics;
      }(),
      builder: (context, snapshot) {
        if (snapshot.hasError) return Center(
          child: Text("An error occurred while loading data, there is the error message: ${snapshot.error}", style: TextStyle(color: Colors.red), textAlign: TextAlign.center,),
        );
        if (snapshot.hasData) return ListView(
          children: <Widget>[
            SizedBox(height: widget.paddingHeight),
            ...snapshot.data.map((e) => _buildItems(e)).toList(),
            SizedBox(height: 80.0),
          ],
        );
        return Center(
          child: CircularProgressIndicator(),
        );
      },
    );
    return buildingWidget;
  }

  Widget _buildItems(Topic topic) {
    Widget buildingWidget;
    Color colorsOfBadges = Theme.of(context).primaryColor;//Theme.of(context).textTheme.bodyText2.color.withOpacity(0.3);
    final String heroTag = "${this.widget.pageIndex}:${topic.topicId}:${topic.userId}";

    buildingWidget = Container(
      decoration: BoxDecoration(
        color: Theme.of(context).backgroundColor,
        borderRadius: BorderRadius.circular(12.0),
      ),
      margin: EdgeInsets.all(10.0),
      padding: EdgeInsets.all(8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          buildAuthorHeader(
            context,
            avatarUrl: topic.userAvatar,
            userKind: topic.userTitle,
            userName: topic.userNickName,
            heroTag: heroTag,
          ),
          Divider(color: Theme.of(context).scaffoldBackgroundColor, height: 5.0, thickness: 1.0,),
          Text(topic.title, style: TextStyle(color: Theme.of(context).primaryColor, fontSize: 14.0, fontWeight: FontWeight.bold),),
          Row(
            children: <Widget>[
              Expanded(
                child: Text(topic.subject, maxLines: topic.imageList.isEmpty ? 4 : 3, overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.subtitle2),
              ),
              _buildTopicListImages(topic),
            ],
          ),
          Divider(color: Theme.of(context).scaffoldBackgroundColor, height: 5.0, thickness: 1.0,),
          IconTheme(data: IconThemeData(size: 14.0, color: colorsOfBadges), child: DefaultTextStyle(
            style: TextStyle(fontSize: 11.0, color: colorsOfBadges),
            child: Row(
              children: <Widget>[
                if (topic.imageList.isNotEmpty) ...[
                  buildBadge(context, text: SizedBox(), icon: Icon(Icons.image)),
                  SizedBox(width: 5.0,),
                ],
                buildBadge(context, icon: Icon(Icons.remove_red_eye), text: Text("${topic.hits}")),
                SizedBox(width: 5.0,),
                buildBadge(context, icon: Icon(Icons.message), text: Text("${topic.replies}")),
                buildBadge(context, icon: Icon(CupertinoIcons.tags_solid), text: Text(topic.boardName)),
                Spacer(),
                buildBadge(context, text: Text(Intl.DateFormat("yyyy-MM-dd HH-mm").format(DateTime.fromMillisecondsSinceEpoch(int.parse(topic.lastReplyDate))), textDirection: TextDirection.ltr,), icon: Icon(Icons.timer))
              ],
            ),
          )
          )
        ],
      ),
    );
    buildingWidget = InkWell(
      child: buildingWidget,
      onTap: (){
        Navigator.of(context).push(MaterialPageRoute(builder: (context) => TopicDetailsPage(topic: topic, heroTag: heroTag,),));
      },
    );
    return buildingWidget;
  }
  Widget _buildTopicListImages(Topic topic) {
    if (topic.imageList.isNotEmpty) {
      final imageList = topic.imageList.length > 2 ? topic.imageList.getRange(0, 3) : topic.imageList;
      var imageIndex = 0;
      final ratio = 0.3;
      final size = 70.0;
      return Container(
        height: size,
        width: size + (imageList.length - 1) * (ratio * 70),
        child: Stack(
          children: imageList.map((imageUrl){
            var index = imageIndex++;
            return Positioned(
              width: size,
                height: size,
                left: (index * size) * ratio,
                child: Container(
                    decoration: BoxDecoration(
                      color: Theme.of(context).scaffoldBackgroundColor,
                      borderRadius: BorderRadius.circular(size / 2.0)
                    ),
                  padding: EdgeInsets.all(3.0),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(size - 6),
                    child: CachedNetworkImage(imageUrl: imageUrl, fit: BoxFit.cover, placeholderFadeInDuration: Duration(seconds: 2), placeholder: (context, url) => Container(color: Colors.black.withOpacity(0.02),),),
                  ),
                )
            );
          }).toList(),
        ),
      );
    }
//      return ClipRRect(borderRadius: BorderRadius.circular(35.0), child: CachedNetworkImage(imageUrl: topic.imageList.first, width: 70.0, height: 70.0, fit: BoxFit.cover,),);
    return SizedBox();
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

Widget buildBadge(BuildContext context, {Widget text, Widget icon}){
  return Container(
    padding: EdgeInsets.all(4.0),
    child: Row(
      children: <Widget>[
        icon,
        SizedBox(width: 3.0,),
        text,
      ],
      mainAxisSize: MainAxisSize.min,
    ),
    decoration: BoxDecoration(
        color: Theme.of(context).scaffoldBackgroundColor,
        borderRadius: BorderRadius.circular(15.0)
    ),
  );
}

List<Widget> _buildDotDotDotDecoration(BuildContext context) => List.generate(3, (index) => Container(
  width: 10.0,
  height: 10.0,
  decoration: BoxDecoration(
      color: Theme.of(context).scaffoldBackgroundColor,
      borderRadius: BorderRadius.circular(5)
  ),
  margin: EdgeInsets.symmetric(horizontal: 3.0),
));

Widget buildAuthorHeader(BuildContext context, {String userName, String avatarUrl, String userKind, Object heroTag}) {
  Widget buildingWidget = CircleAvatar(
    backgroundImage: NetworkImage(avatarUrl),
    radius: 25.0,
  );
  if (heroTag != null) buildingWidget = Hero(
    child: buildingWidget,
    tag: heroTag,
  );
  return Row(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      buildingWidget,
      SizedBox(width: 5.0,),
      Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(userName),
          SizedBox(height: 5.0,),
          Text(userKind, style: Theme.of(context).textTheme.subtitle2),
        ],
      ),
      Spacer(),
      ..._buildDotDotDotDecoration(context)
    ],
  );
}
